package servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import bean.Type;
import common.base.BaseServlet;
import common.util.CustomBeanUtils;
import common.util.UUIDUtils;
import service.TypeService;
import service.impl.TypeServiceImpl;

@WebServlet("/TypeServlet")
public class TypeServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
	public String queryAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//调用业务层查询全部分类
		TypeService typeService = new TypeServiceImpl();
		List<Type> types = typeService.queryAll();
		//将集合转换成Json字符串
		Gson gson = new Gson();
		String jsonStr = gson.toJson(types);
		
		//向客户端回传数据
		response.getWriter().write(jsonStr);
		
		return null;
	}

	//添加类型
	public String addType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得请求参数信息
		Map<String, String[]> parameterMap = request.getParameterMap();	
		Type type = CustomBeanUtils.populate(Type.class, parameterMap);
		type.setTypeId(UUIDUtils.getId());
			  
		//调用service执行添加类型操作
		TypeService typeService = new TypeServiceImpl();
		boolean success = typeService.insert(type);
		
		String message = null;
		//成功
		if (success) {
			message="类型添加成功";
			request.getSession().setAttribute("message", message);
		} else {
			message="类型添加失败";
			request.getSession().setAttribute("message", message);
		}
		response.sendRedirect(request.getContextPath() + "/admin/type-add.jsp");
		return null;
	}
	
}
